using System.Text.Json;
using System.Text.Json.Serialization;

namespace Vin.Tool.Core.JsonCategory.Converters;

public class ObjectToJsonStringConverter<T> : JsonConverter<T>
{
    public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType == JsonTokenType.Null || reader.TokenType == JsonTokenType.None)
            return default;
        if (reader.TokenType == JsonTokenType.String)
        {
            var enumText = reader.GetString();
            if (string.IsNullOrEmpty(enumText))
                return default;
            return enumText.ToObject<T>();
        }

        return default;
    }

    public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToCamelCaseJson());
    }
}